package com.sdhs.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtils {
    // 固定密钥（必须16/24/32字节对应128/192/256位AES）
    private static final String SECRET_KEY = "FixedSecretKey12"; // 16字节
    // 固定初始化向量（必须16字节）
    private static final String IV = "1234567890123456"; // 16字节
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    /**
     * 加密方法
     * @param data 要加密的数据
     * @return 加密后的Base64编码字符串
     */
    public static String encrypt(String data) throws Exception {
        // 检查密钥长度
        if (SECRET_KEY.getBytes(StandardCharsets.UTF_8).length != 16) {
            throw new IllegalArgumentException("密钥长度必须为16字节(128位)");
        }

        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密方法
     * @param encryptedData 加密后的Base64编码字符串
     * @return 解密后的原始字符串
     */
    public static String decrypt(String encryptedData) throws Exception {
        // 检查密钥长度
        if (SECRET_KEY.getBytes(StandardCharsets.UTF_8).length != 16) {
            throw new IllegalArgumentException("密钥长度必须为16字节(128位)");
        }

        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
    public static BigDecimal safeConvertToBigDecimal(String str) {
        try {
            return new BigDecimal(str.trim());
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }
}
